<?php

/**
 * Tên class được đặc tên từ tên modules tiếp đến là tên controller: Tenmodule_TencontrollerController
 */

class Enterprise_EnterpriseController extends Zend_Controller_Action {

    /**
    * List enterprise
    *
    * @return void
    */
    public function listAction() {
        $request = $this->getRequest();

        $lang = $request ->getParam('lang');
        $this->view->assign('lang', $lang);

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Enterprise basic model access to db
         */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Enterprise accont payment model access to db
         */
        $paymentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getPaymentDao();
        $paymentDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage   = 20;
        $offset    = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();
        $exp = array(
            'deleted' => 0
        );
        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list enterprise
        */
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            $exp['id'] = $purifier->purify(@$userAccount->enterprise_id);
        }
		
        $sltProfession = null;
        $sltApplication = null;
        if ($request->isPost()) {
            $id           = $request->getPost('id');
			$company_name = $request->getPost('company_name',null);
			$registration_number 	= $request->getPost('registration_number',null);
			$registration_date_from = $request->getPost('registration_date_from',null);
			$registration_date_to 	= $request->getPost('registration_date_to',null);
			$sltProfession			= $request->getPost('sltProfession',null);
			$sltApplication			= $request->getPost('sltApplication',null);
			if($sltApplication=="") $sltApplication = null;
            if(Core_Services_RuleChecker::isAllowed('all-list')){
				
                if ($id) {
                    $exp['id'] = $purifier->purify($id);
                }
				if($company_name){
					$exp["company_name"] = $company_name;
				}
				if($registration_number){
					$exp["registration_number"] = $registration_number;
				}
				if($registration_date_from){
					$exp["registration_date_from"] = $registration_date_from;
				}
				if($registration_date_to){
					$exp["registration_date_to"] = $registration_date_to;
				}
				if($sltProfession){
					$exp["profession"] = $sltProfession;
				}	
				if($sltApplication){
					$exp["application"] = $sltApplication;
				}
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        } else {
			$company_name           = "";
			$registration_number 	= "";
			$registration_date_from = "";
			$registration_date_to 	= "";	
			$this->sltProfession   = null;	
            $params = $request->getParam('q');
            if ($params != null) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }

        $enterprise = $enterpriseDao->find($offset, $perPage, $exp);
        $total       = $enterpriseDao->count($exp);
		
		$professions = $enterpriseDao->getProfessions();
		$this->view->assign("professions",$professions);
		
        /**
         * Get account_valid_until_date by enterprise id
         */
         $arValidDate = array();
         foreach($enterprise as $row){
            $payment = $paymentDao->getById($row->id);
            if($payment){
                $arValidDate[$row->id] = $payment;
            }
         }
         $this->view->assign('arValidDate', $arValidDate);

        /**
        * Paginator
        */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($enterprise, $total));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

		$this->view->assign("company_name",$company_name);
		$this->view->assign("registration_number",$registration_number);
		$this->view->assign("registration_date_from",$registration_date_from);
		$this->view->assign("registration_date_to",$registration_date_to);
		$this->view->assign('sltProfession',$sltProfession);
		$this->view->assign('sltApplication',$sltApplication);
		
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('enterprise', $enterprise);
        $this->view->assign('numEnterprise', $total);

        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array(), 'enterprise_enterprise_list'),
            'itemLink' => (null == $params)
                            ? 'page-%d'
                            : 'page-%d/' . '?q=' . $params,
        ));
    }

    /*
     * Add new enterprise
     * @return void
     */
    public function addAction() {
        $request = $this->getRequest();

        /**
        * Get connectino to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Enterprise model access to data
         **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
        * Product model access to data
        **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        /**
        * Enterprise info models access to data
        **/
        $infoDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
        $infoDao->setDbConnection($conn);

        /**
         * Get currency
         **/
        $currency = $productDao->getCurrency();
        $this->view->assign('currency', $currency);

        /**
         * Get professtions
         **/
         $professions = $enterpriseDao->getProfessions();
         $this->view->assign('professions', $professions);

        if($request->isPost()){
            $count = $enterpriseDao->count(array('deleted' => 0));
            if($count >= 500){
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage($this->view->translator('enterprise_add_full_account'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'enterprise_enterprise_add'));
            }

            $strProfessions = ',';
            $arrId = $request->getPost('professions_id');
            foreach($arrId as $row){
                $strProfessions .= $row.',';
            }

            /**
            * Add new enterprise
            */
            $enterprise = new Enterprise_Models_Enterprise(array(
                'frontend_active'        => $request->getPost('frontend_active'),
                'backend_active'         => $request->getPost('backend_active'),
                'company_name_vn'        => $request->getPost('company_name_vn'),
                'company_name_en'        => $request->getPost('company_name_en'),
                'contact_email'          => $request->getPost('contact_email'),
                'contact_tel'            => $request->getPost('contact_tel'),
                'contact_fax'            => $request->getPost('contact_fax'),
                'contact_address'        => $request->getPost('contact_address'),
                'bank_name_vnd'          => $request->getPost('bank_name_vnd'),
                'bank_name_usd'          => $request->getPost('bank_name_usd'),
                'bank_account_vnd'       => $request->getPost('bank_account_vnd'),
                'bank_account_usd'       => $request->getPost('bank_account_usd'),
                'bank_account_owner_vnd' => $request->getPost('bank_account_owner_vnd'),
                'bank_account_owner_usd' => $request->getPost('bank_account_owner_usd'),
                'registration_number'    => $request->getPost('registration_number'),
                'registration_date'      => date('Y-m-d', strtotime($this->convertDateFormat($request->getPost('registration_date')))),
                'registration_city'      => $request->getPost('registration_city'),
                'deleted'                => 0,
                'professions_id'         => $strProfessions,
                'currency'               => $request->getPost('currency'),
                'application'            => 0,

            ));
            $enterpriseId = $enterpriseDao->add($enterprise);

            /**
             * Update enterprise id to enterprise_professions
             **/
            if($enterpriseId){
                foreach($arrId as $id){
                    $arrPro = array(
                        'professions_id' =>    $id,
                        'enterprise_id'  =>    $enterpriseId,
                    );
                    $enterpriseDao->updateProfessions($arrPro);
                }

                /**
                * Auto add enterprise default
                **/
                if($enterprise->frontend_active || $enterprise->backend_active){
                    $infoDao->autoAdd($enterpriseId);
                }
            }

            $this->_helper->getHelper('FlashMessenger')
                ->addMessage($this->view->translator('enterprise_add_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'enterprise_enterprise_add'));
        }
    }

    /**
     * Edit enterprise
     * @return void
     */
    public function editAction() {
        $request = $this->getRequest();
        $id = $request->getParam('enterprise_id');
        $this->view->assign('enterprise_id', $id);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Enterprise model access ta data
         **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
        * Product model access to data
        **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        /**
        * Enterprise info models access to data
        **/
        $infoDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
        $infoDao->setDbConnection($conn);

        /**
         * Get currency
         **/
        $currency = $productDao->getCurrency();
        $this->view->assign('currency', $currency);

        /**
         * Get professtions
         **/
         $professions = $enterpriseDao->getProfessions();
         $this->view->assign('professions', $professions);

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();

         /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list enterprise
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(@$userAccount->enterprise_id){
                if($id != @$userAccount->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        $enterprise = $enterpriseDao->getById($id);
        if (null == $enterprise) {
            return;
        }
        $this->view->assign('enterprise', $enterprise);

        if ($request->isPost()) {

            $strProfessions = ',';
            $arrId = ($request->getPost('professions_id'))?$request->getPost('professions_id'):array();
            if($arrId){
                foreach($arrId as $row){
                    $strProfessions .= $row.',';
                }
            }

            /**
            * Compare array professions news and old
            * @return array is values diffrent of professions news and old
            **/
            $old_professions = explode(',', $request->getPost('old_professions'));
            $addResult = array_diff($arrId, $old_professions);
            $deleteResult = array_diff($old_professions,$arrId);

            $frontend_active        = $request->getPost('frontend_active');
            $backend_active         = $request->getPost('backend_active');
            $company_name_vn        = $request->getPost('company_name_vn');
            $company_name_en        = $request->getPost('company_name_en');
            $contact_email          = $request->getPost('contact_email');
            $contact_tel            = $request->getPost('contact_tel');
            $contact_fax            = $request->getPost('contact_fax');
            $contact_address        = $request->getPost('contact_address');
            $bank_name_vnd          = $request->getPost('bank_name_vnd');
            $bank_name_usd          = $request->getPost('bank_name_usd');
            $bank_account_vnd       = $request->getPost('bank_account_vnd');
            $bank_account_usd       = $request->getPost('bank_account_usd');
            $bank_account_owner_vnd = $request->getPost('bank_account_owner_vnd');
            $bank_account_owner_usd = $request->getPost('bank_account_owner_usd');
            $registration_number    = $request->getPost('registration_number');
            $registration_date      = date('Y-m-d', strtotime($this->convertDateFormat($request->getPost('registration_date'))));
            $registration_city      = $request->getPost('registration_city');
            $delete                 = 0;
            $currency               = $request->getPost('currency');
            $application            = $request->getPost('application',0);;

            $enterprise->frontend_active        = $frontend_active;
            $enterprise->backend_active         = $backend_active;
            $enterprise->company_name_vn        = $company_name_vn;
            $enterprise->company_name_en        = $company_name_en;
            $enterprise->contact_email          = $contact_email;
            $enterprise->contact_tel            = $contact_tel;
            $enterprise->contact_fax            = $contact_fax;
            $enterprise->contact_address        = $contact_address;
            $enterprise->bank_name_vnd          = $bank_name_vnd;
            $enterprise->bank_name_usd          = $bank_name_usd;
            $enterprise->bank_account_vnd       = $bank_account_vnd;
            $enterprise->bank_account_usd       = $bank_account_usd;
            $enterprise->bank_account_owner_vnd = $bank_account_owner_vnd;
            $enterprise->bank_account_owner_usd = $bank_account_owner_usd;
            $enterprise->registration_number    = $registration_number;
            $enterprise->registration_date      = $registration_date;
            $enterprise->registration_city      = $registration_city;
            $enterprise->delete                 = $delete;
            $enterprise->professions_id         = $strProfessions;
            $enterprise->currency               = $currency;
            $enterprise->application            = $application;

            /**
            * Update date enterprise
            **/
            $bool = $enterpriseDao->update($enterprise);

            /**
            * Auto add enterprise default
            **/
            if($frontend_active || $backend_active){
                $infoEnter = $infoDao->bkgetById($id);
                if(count($infoEnter) <= 0){
                    $infoDao->autoAdd($id);
                }
            }

            /**
             * Update enterprise_id to professions
             **/
            if($bool){

                /**
                * Add enterprise_id
                **/
                if($addResult){
                    foreach($addResult as $row){
                        $arrPro = array(
                            'professions_id' =>    $row,
                            'enterprise_id'  =>    $id,
                        );
                        $enterpriseDao->updateProfessions($arrPro);
                    }
                }

                /**
                 * Delete enterprise_id
                 **/
                 if($deleteResult){
                    foreach($deleteResult as $row){
                        if($row){
                            $arrPro = array(
                                'professions_id' =>    $row,
                                'enterprise_id'  =>    $id,
                            );
                            $enterpriseDao->updateProfessions1($arrPro);
                        }
                    }
                }                
                /**
	             * START: Chỉnh tiền tệ trong enterprise -> chỉnh tiền tệ trong product và tính lại tiền SP (giá bán, shipping product in cart)
	             **/
				$rate_input = $request->getParam('rate_input');  
				if($rate_input == "")
				{
					$rate_input = 1;              	
				} 
				$productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
	        	$productDao->setDbConnection($conn);
				
	        	$arrRate = array(
	        		'product_price_currency' => $currency,
	        		'rate' => $rate_input,
	        		'enterprise_id' => $id
	        	);
	        	$productDao->updateRate($arrRate);   
	        	/**
	             * END: Chỉnh tiền tệ trong enterprise -> chỉnh tiền tệ trong product và tính lại tiền SP (giá bán, shipping product in cart)
	             **/
            }
            $this->_helper->getHelper('FlashMessenger')
                ->addMessage($this->view->translator('enterprise_edit_success'));                       
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('enterprise_id' => $id), 'enterprise_enterprise_edit'));
        }
    }

    /**
    * Create and edit enterprise payment info
    * @return void
    */
    public function paymentInfoAction(){
        $request = $this->getRequest();
        $id = $request->getParam('enterprise_id');
        $this->view->assign('enterprise_id', $id);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Payment access to data
         **/
        $paymentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getPaymentDao();
        $paymentDao->setDbConnection($conn);

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();

         /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list enterprise
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(@$userAccount->enterprise_id){
                if($id != @$userAccount->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        $paymentDB = $paymentDao->getById($id);
        $payment = $paymentDB;
        if(null == $paymentDB){
            $payment = new Enterprise_Models_Payment(array());
        }
        $payment->enterprise_id = $id;
        $this->view->assign('payment', $payment);

        if($request->isPost()){
            $last_payment_date = ($request->getPost('last_payment_date'))?date('Y-m-d', strtotime($this->convertDateFormat($request->getPost('last_payment_date')))):null;
            $account_valid_until_date = ($request->getPost('account_valid_until_date'))?date('Y-m-d', strtotime($this->convertDateFormat($request->getPost('account_valid_until_date')))):null;

            $payment->last_payment_date = $last_payment_date;
            $payment->last_payment_amount = $request->getPost('last_payment_amount');
            $payment->account_valid_until_date = $account_valid_until_date;

            if(null != $payment->last_payment_date && null != $payment->last_payment_amount && null != $payment->account_valid_until_date){
                if(null == $paymentDB){
                    $paymentDao->add($payment);
                }else{
                    $paymentDao->update($payment);
                }
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage($this->view->translator('enterprise_payment_info_edit_success'));
            }
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('enterprise_id' => $id), 'enterprise_enterprise_payment_info'));
        }
    }

    /**
    * Create and edit enterprise info
    * @return void
    */
    public function enterpriseInfoAction(){
        $request = $this->getRequest();
        $id = $request->getParam('enterprise_id');
        $this->view->assign('enterprise_id', $id);

        $lang = $request ->getParam('lang');
        $this->view->assign('lang', $lang);

        $number = 5;/*The number record will be created or update*/
        $this->view->assign('number', $number);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Enterprise info access to data
        **/
        $infoDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getInfoDao();
        $infoDao->setLang($lang);
        $infoDao->setDbConnection($conn);

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();

         /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list enterprise
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(@$userAccount->enterprise_id){
                if($id != @$userAccount->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        $infoDB = $infoDao->bkgetById($id);
        $arrInfo = array();
        if(null != $infoDB){
            foreach($infoDB as $row){
                $arrInfo[$row->info_number] = $row;
            }
        }
        $this->view->assign('info', $arrInfo);

        if($request->isPost()){
            $infoDao->bkdelete($id);/*Delete current enterprise info before add*/
            for($i=1;$i<=$number;$i++){
                $info_title = $request->getPost('info_title_'.$i);
                $info_string = $request->getPost('info_string_'.$i);
                $info = new Enterprise_Models_Info(array(
                        'enterprise_id'  => $id,
                        'info_title'     => $info_title,
                        'info_string'    => $info_string,
                        'info_number'    => $i,
                        'language'       => $lang,
                ));
                $infoDao->add($info);
                /*if(null != trim($info->info_string)){
                    $infoDao->add($info);
                }*/
            }
            $this->_helper->getHelper('FlashMessenger')
                    ->addMessage($this->view->translator('enterprise_info_edit_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('enterprise_id' => $id), 'enterprise_enterprise_info').'/'.$lang);
        }
    }

    /**
    * Create and list user account of enterprise
    * @return void
    */
    public function userAccountAction(){
        $request = $this->getRequest();
        $id = $request->getParam('enterprise_id');
        $this->view->assign('id', $id);

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();

         /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list enterprise
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(@$userAccount->enterprise_id){
                if($id != @$userAccount->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        $userAccount = $userAccountDao->getUserAccountBy($id);
        $this->view->assign('userAccount', $userAccount);
    }
	
	public function edituserAccountAction() 
	{
		$request = $this->getRequest();
		
		$userId  = $request->getParam('user_id');
		$enterprise_id = $request->getParam('enterprise_id');
		$this->view->assign('enterprise_id',$enterprise_id);
		
		$conn = Tomato_Db_Connection::factory()->getMasterConnection();
		$userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();				
		$userDao->setDbConnection($conn);

		$conn = Tomato_Db_Connection::factory()->getMasterConnection();
		$enterpriseAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();				
		$enterpriseAccountDao->setDbConnection($conn);

		$user  = $userDao->getById($userId);
		$enAccount = $enterpriseAccountDao->getByUser($userId);
		
		
		$this->view->assign('enterprise_id',$enAccount->enterprise_id);
		$this->view->assign('user', $user);
		
		if ($request->isPost()) {
			$fullname = $request->getPost('full_name');
			$username = $request->getPost('username');
			$password = $request->getPost('confirmPassword');
			$email 	  = $request->getPost('email');
			
			$userObj  = $userDao->getById($userId);
			$roleId	  = $userObj->role_id;
			$user = new Core_Models_User(array(
				'user_id' 	=> $userId,
				'user_name' => $username,
				'password' 	=> $password,
				'full_name' => $fullname,
				'email' 	=> $email,
				'role_id' 	=> $roleId,
			));
			$result = $userDao->update($user);
			if ($result > 0) {
				$this->_helper->getHelper('FlashMessenger')
					->addMessage($this->view->translator('user_edit_success'));
				$this->_redirect($this->view->serverUrl() . $this->view->url(array('user_id' => $userId), 'enterprise_user_account_edit'));
			}
		}
	}

    /**
     * Ajax to create user account for enterpirse
     * @return void
     */
    public function userCreateAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $id = $request->getParam('id');

        /**
         * The array role
         * */
        $arrRole = array(
            '1' => 'tong quan ly doanh nghiep',
            '2' => 'quan ly san xuat',
            '3' => 'nhan vien san xuat',
            '4' => 'nhan vien san xuat',
            '5' => 'nhan vien san xuat',
            '6' => 'nhan vien san xuat',
            '7' => 'nhan vien san xuat',
            '8' => 'quan ly thu mua',
            '9' => 'quan ly ban hang',
            '10' => 'quan ly marketing pr',
        );

        /**
         * The array user account will be created
         * */
        $arrUser = array(
            '1' => 'tongquanly',
            '2' => 'quanlysanxuat',
            '3' => 'nhanviensanxuat1',
            '4' => 'nhanviensanxuat2',
            '5' => 'nhanviensanxuat3',
            '6' => 'nhanviensanxuat4',
            '7' => 'nhanviensanxuat5',
            '8' => 'quanlythumua',
            '9' => 'quanlybanhang',
            '10' => 'quanlymarketing',
        );
        $number = count($arrUser);

        if($request->isPost()){
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();

            /**
            * Core User model access to db
            */
            $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
            $userDao->setDbConnection($conn);

            /**
            * Enterprise User model access to db
            */
            $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
            $userAccountDao->setDbConnection($conn);

            $arrUserInfo = array();
            for($i=1;$i<=$number;$i++){
                $role = $userAccountDao->getRoleByName($arrRole[$i]);
                if($role){
                    $fullname  = null;
                    $username  = $arrUser[$i].'_'.$id;
                    $password  = $this->generatePassword();
                    $email        = null;
                    $roleId    = $role->role_id;
                    $user = new Core_Models_User(array(
                        'user_name'      => $username,
                        'password'       => $password,
                        'full_name'      => 'Họ tên',
                        'email'          => "email{$i}_{$id}@email.com",
                        'is_active'      => 1,
                        'created_date'   => date('Y-m-d H:i:s'),
                        'logged_in_date' => null,
                        'is_online'      => 0,
                        'role_id'        => $roleId,
                    ));
                    $uid = $userDao->add($user);
                    if($uid){
                        $userAccount = new Enterprise_Models_User(array(
                            'enterprise_id' => $id,
                            'user_id' => $uid
                        ));
                        $userAccountDao->add($userAccount);

                        /**
                        * The array to view message
                        */
                        $arrUserInfo[] = array('0' => $username, '1' => $password);
                    }
                }else{
                    die('Not found role id');
                }
            }

            /**
             * Load user just to be add
             */
            $userAccount = $userAccountDao->getUserAccountBy($id);
            $this->view->assign('userAccount', $userAccount);
            $this->view->assign('arrUserInfo', $arrUserInfo);
        }
    }

    /**
    * Update enterprise width deleted = 1
    * @return void
    */
    public function deleteAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        $id = $request->getParam('id');
        $string = 'RESULT_ERROR';

        if ($request->isPost()) {
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
            $enterpriseDao->setDbConnection($conn);

            $enterprise = $enterpriseDao->getById($id);
            if (null == $enterprise) {
                $this->getResponse()->setBody('RESULT_NOT_FOUND');
                return;
            }
            $enterpriseDao->delete($enterprise);
            $string = 'RESULT_OK';
        }
        $this->getResponse()->setBody($string);
    }

    /**
     * Format date to strtotime function use
     * @return string
     */
    public function convertDateFormat($time){
        $a = explode("/", $time);
        $ts = $a[2].'/'.$a[1].'/'.$a[0];
        return $ts;
    }

    /**
     * The function to auto generatePassword
     * @return string
     */
    public function generatePassword($length=9, $strength=0) {
        $vowels = 'aeuy';
        $consonants = 'bdghjmnpqrstvz';
        if ($strength & 1) {
            $consonants .= 'BDGHJLMNPQRSTVWXZ';
        }
        if ($strength & 2) {
            $vowels .= "AEUY";
        }
        if ($strength & 4) {
            $consonants .= '23456789';
        }
        if ($strength & 8) {
            $consonants .= '@#$%';
        }

        $password = '';
        $alt = time() % 2;
        for ($i = 0; $i < $length; $i++) {
            if ($alt == 1) {
                $password .= $consonants[(rand() % strlen($consonants))];
                $alt = 0;
            } else {
                $password .= $vowels[(rand() % strlen($vowels))];
                $alt = 1;
            }
        }
        return $password;
    }
}